/**
 * @Date   2016/5/18
 * @author speed
 * UI图层管理器
 */
class UIManager {
    private static _instance:UIManager;
    // 场景层 如 战场、主城、副本战场之类的
    private  sceneLayer:egret.Sprite;        
    // 主UI层 如 底部功能栏
    public mainLayer:eui.Group ;
    // 弹窗层 如 设置、背包、装备之类的
    public popWinLayer: eui.Group; 
    // 确认窗 层       
    private alertWinLayer: eui.Group;  
    // 特效层 如 闪烁、飘字之类的
    public effectLayer:eui.Group;   
   

    private tipLayer: egret.Sprite;
    private lockScreenLayer: egret.Sprite;
    private loadingLayer:egret.Sprite;
    // private loadingView:LoadingView;
    // private alertView: AlertView;


    
    private lockDefaultColor: number = 0x000000;
    private lockDefaultAlpha:number = 0.5;
    private isScreenLocked:boolean = false;
    private layerArr:Array<egret.DisplayObjectContainer> = [];
    private tipArr: Array<any> = [];
    private tipStartY:number = 600;
    private tipEndY:number = 300;
    private temSoundEnable:boolean=false;
    
	public constructor() {
    	if(UIManager._instance){
            throw new Error("UIManager单例");
    	}
	}
	
	//初始化图层
	public initLayer():void{
	    var self = UIManager.instance;
	    self.sceneLayer = self.createDisplayObjectContainer();
        self.mainLayer = self.createDisplayObjectGroup();
        self.lockScreenLayer = self.createDisplayObjectContainer();
        self.popWinLayer = self.createDisplayObjectGroup();
        self.alertWinLayer = self.createDisplayObjectGroup();
        self.tipLayer = self.createDisplayObjectContainer();
        self.loadingLayer = self.createDisplayObjectContainer();
        self.effectLayer = self.createDisplayObjectGroup();

       

        App.root.addEventListener(egret.Event.RESIZE,self.onResize,self);
        App.root.stage.addEventListener(egret.Event.DEACTIVATE,self.onDeactivate,self);
        App.root.stage.addEventListener(egret.Event.ACTIVATE,self.onActivate,self);
	}
	
    private createDisplayObjectContainer(): egret.Sprite{
        var self = UIManager.instance;
        var root: eui.UILayer = App.root;
        var sprite: egret.Sprite = new egret.Sprite();
        sprite.touchEnabled = false;
        sprite.width = root.stage.stageWidth;
        sprite.height = root.stage.stageHeight;
        self.layerArr.push(sprite);
        App.root.addChild(sprite);
        return sprite;
	}
	
    private createDisplayObjectGroup(lockScreen?:boolean): eui.Group {
        var self = UIManager.instance;
        var root: eui.UILayer = App.root;
        var group: eui.Group = new eui.Group();
        group.touchEnabled = false;
        group.width = root.stage.stageWidth;
        group.height = root.stage.stageHeight;
        self.layerArr.push(group);
        App.root.addChild(group);
        return group;
    }
    
    //是否H5
    public isH5(): boolean {
        return egret.Capabilities.runtimeType == egret.RuntimeType.WEB;
    }
    
    //egret获取url参数的方法         
    public getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i");
        var r = window.location.search.substr(1).match(reg);
        if(r != null) {
            return r[2];
        }
        return null;
    }
    
    public showAlert2(title:string,msg:string)
    {
        // var data:AlertData=new AlertData();
        // data.title=title;
        // data.desc=msg;
        // this.showAlert(data);
    }
    
    //显示二次确认框
    // public showAlert(data: AlertData): void {
    //     var self = UIManager.instance;
    //     if(!self.alertView)
    //         self.alertView = new AlertView(data);
    //         self.alertView.scaleX = 0.8 ;
    //         self.alertView.scaleY = 0.8 ;
    //         self.alertView.horizontalCenter = 0;
    //         self.alertView.verticalCenter = 0;
    //     if(!self.alertView.parent) {
    //         self.showLockScreen();
    //         self.alertWinLayer.addChild(self.alertView);
    //     }
    //     egret.Tween.get(self.alertView).wait(20).to({scaleX:1,scaleY:1},200 , egret.Ease.backInOut) ;
    //     self.alertView.setData(data);
    // }
	
    // //移除二次确认框
    // public removeAlert(): void {
    //     var self = UIManager.instance;
    //     if(self.alertView && self.alertView.parent) {
    //         egret.Tween.get(self.alertView).to({scaleX:0.7,scaleY:0.7},300 , egret.Ease.backIn).call(function(){
    //             self.alertView.parent.removeChild(self.alertView);
    //             self.removeLockScreen();
    //         }) ;
    //     }
    // }
	
	// //显示加载动画
    // public showLoading(msg):void{
    //     var self = UIManager.instance;
	//     if(!self.loadingView){
    //         self.loadingView = new LoadingView();   
	//     }
    // 	if(!self.loadingView.parent){
    // 	    self.loadingLayer.addChild(self.loadingView);
    // 	}
    //     self.loadingView.setMsg(msg);
	// }
	
	// //移除加载动画
    // public removeLoading():void{
    //     var self = UIManager.instance;
	//     if(self.loadingView && self.loadingView.parent){
	//         self.loadingView.parent.removeChild(self.loadingView);
	//     }
	// }
	
	
	/**
	 * 显示场景
	 * @param cls  可以是类名，也可以是类定义
	 * @param param  构造函数的参数，并添加setData方法
	 * 构造函数 传参了的场景 都要写setData方法
	 */
    public showScene(cls,param?: any,processFun?:Function):any{
        var self = UIManager.instance;
        var scene = utils.WinUtil.showScene(cls,param);
        LogManager.log("show Scene:" + egret.getQualifiedClassName(scene));
        utils.WinUtil.loadResource(cls,function() {
            if(scene) {
                self.sceneLayer.removeChildren();
                self.sceneLayer.addChild(scene);
                LogManager.log("add Scene:" + egret.getQualifiedClassName(scene));
            }
        },processFun);
        return scene;
	}
	
	
	/**
	 * 移除场景
	 * @param scene 场景实力
	 */
	public removeScene(scene):void{
	    var self = UIManager.instance;
	    if(self.sceneLayer.contains(scene)){
	        self.sceneLayer.removeChild(scene);
	    }
	}

    /**
     * 显示主UI层 
     */
	public showMainUI(cls,param?: any,processFun?:Function):any{
        var self = UIManager.instance;
        var scene = utils.WinUtil.showScene(cls,param);
        LogManager.log("showMainUI:" + egret.getQualifiedClassName(scene));
        utils.WinUtil.loadResource(cls,function() {
            if(scene) {
                self.mainLayer.removeChildren();
                self.mainLayer.addChild(scene);
                LogManager.log("addMainUI:" + egret.getQualifiedClassName(scene));
            }
        },processFun);
        return scene;
	}
    /**
     * 移除主UI层
     */
    public removeMainUI(ui){
        var self = UIManager.instance;
        if(self.mainLayer.contains(ui)){
	        self.mainLayer.removeChild(ui);
	    }
        
    }

	/**
     * 显示窗体
     * 构造函数 传参了的长提 都要写setData方法
     */
    public popWin(cls,param?: any,isLockScreen?:boolean):any{
        var self = UIManager.instance;
        var win = utils.WinUtil.showScene(cls,param);
        utils.WinUtil.loadResource(cls,function() {
            if(win) {
                win.scaleX = 0.5 ;
                win.scaleY = 0.5 ;
                win.alpha = 0 ;
                win.horizontalCenter = 0;
                win.verticalCenter = 0;
                if(isLockScreen) {
                    self.showLockScreen();
                }
                self.popWinLayer.removeChildren();
                self.popWinLayer.addChild(win);
                self.popWinLayer.validateNow();
                egret.Tween.get(win).wait(100).to({scaleX:1,scaleY:1,alpha:1},400 , egret.Ease.backInOut);
            }
        });
        return win;
	}
	
	//移除窗体
	public removeWin(win):void{
        var self = UIManager.instance;
        if(self.popWinLayer.contains(win)) {
            egret.Tween.get(win).to({scaleX:0.5,scaleY:0.5,alpha:0},300 , egret.Ease.backIn).call(function(){
                self.popWinLayer.removeChild(win);
            }) ;
        }
        self.removeLockScreen();
	}
	
	//移除所有窗体
	public removeAllWin():void{
        var self = UIManager.instance;
        self.removeLockScreen();
        self.popWinLayer.removeChildren();
	}
	
	//锁屏
	public showLockScreen(color?:number,alpha?:number):void{
    	var self = UIManager.instance;
    	var color = isNaN(color)  ? self.lockDefaultColor : color;
        var alpha = isNaN(alpha) ? self.lockDefaultAlpha : alpha;
        self.isScreenLocked = true;
        self.lockScreenLayer.visible = true;
	    self.lockScreenLayer.graphics.clear();
        self.lockScreenLayer.graphics.beginFill(color,alpha);
        self.lockScreenLayer.graphics.drawRect(0,0,App.root.stage.stageWidth,App.root.stage.stageHeight);
        self.lockScreenLayer.graphics.endFill();
        self.lockScreenLayer.touchEnabled = true ;
	}
	
	public removeLockScreen():void{
    	var self = UIManager.instance;
        self.isScreenLocked = false;
        self.lockScreenLayer.visible = false;
        self.lockScreenLayer.graphics.clear();   
	}
	
	//显示提示语
    public showTip(tip: string,color = 0xffffff,size: number = 32,sColor = 0x61371f):void{
    	if(!tip || tip.length <= 0)
    	    return;  	
    	else{
            var self = UIManager.instance;
            var totalLen = self.tipArr.length;
            var tempList = self.tipArr.concat([]);
            var group: eui.Group = self.createTip(tip,color,size,sColor);
            self.updateTipList();
            
            group.y = self.tipStartY;
            self.tipLayer.addChild(group);
            self.tipArr.push(group);
            egret.Tween.get(group).to({ y: self.tipStartY - 50 },300).wait(1000).to({ alpha: 0,y: self.tipEndY},300).call(function() {
                var idx = self.tipArr.indexOf(group);
                self.tipLayer.removeChild(group);
                self.tipArr.splice(idx,1);
            })   
    	}
	}

	private updateTipList():void{
        var self = UIManager.instance;
        var totalLen = self.tipArr.length;
        var tempList = self.tipArr.concat([]);
        tempList.forEach(function(toast,idx) {
            if(self.tipLayer.contains(toast)) {
                var toY: number = toast.y - toast.height;
                var time = (toY - self.tipEndY) * 5;
                egret.Tween.removeTweens(toast);
                egret.Tween.get(toast).to({ y: toY },300).wait(100).to({ y: self.tipEndY,alpha: 0 },time).call(function() {
                    var idx = self.tipArr.indexOf(toast);
                    self.tipLayer.removeChild(toast);
                    self.tipArr.splice(idx,1);
                });
            }
        });
	}
	
    private createTip(tip: string,color = 0xffe102,size: number = 24,sColor: number = 0x61371f):eui.Group{
        var label = new eui.Label();
        var group = new eui.Group();
        var tipH:number = 80;
        var endSymbol = tip.indexOf("#H");
        var imgSymbol = tip.indexOf("#A");
        var hLayout:eui.HorizontalLayout = new eui.HorizontalLayout();
        hLayout.horizontalAlign = egret.HorizontalAlign.CENTER;
        hLayout.verticalAlign = egret.VerticalAlign.MIDDLE;
        //group.layout = hLayout;
        
        if(imgSymbol != -1 && endSymbol > 1){
            var imgRes = tip.substring(imgSymbol+3,endSymbol-1);
                var img: eui.Image = new eui.Image();
                img.source=imgRes;
                group.addChild(img);
            tip = tip.substring(endSymbol + 2);
        }
        var img: eui.Image = new eui.Image();
        img.source="bg_tips2_png";
        group.height = img.height;
        group.width = App.root.width;
        group.addChild(img);
        img.horizontalCenter = 0 ;
        img.verticalCenter = 0;
        label.horizontalCenter = 0;
        label.verticalCenter = 0;
        
        label.text = tip;
        label.size = size;
        label.textColor = color;
        label.strokeColor = sColor == 0 ? 0x000 : sColor;
        label.stroke = 2;
        label.fontFamily = "微软雅黑";
        label.touchEnabled = false;

        group.addChild(label);
        group.touchEnabled = false;
        group.touchChildren = false;
        return group;
	}
	
    private onResize(e:egret.Event):void{
        var self = UIManager.instance;
        var width = App.root.width;
        var height = App.root.height;
        self.layerArr.forEach(function(layer,idx){
            layer.width = width;
            layer.height = height;
        });
    }
    
    private onReturnApp(): void {
        // window.location.href = document.referrer;
    }
    
    /**
     * 页面失去焦点的时候调用
     */
    private onDeactivate(): void {
        App.gameIsInBack=true;
        this.temSoundEnable=utils.SoundUtil.getSoundEnable();
        utils.SoundUtil.enableSound(false);
        NotificationManager.instance.sendMsg(NotificationConst.GAME_DEACACTIVE);
    }

    /**
     * 页面失去焦点的时候调用
     */
    private onActivate(): void {
        App.gameIsInBack=false;
        utils.SoundUtil.enableSound(this.temSoundEnable);
        NotificationManager.instance.sendMsg(NotificationConst.GAME_ACTIVE);
    }
    
	public static get instance():UIManager{
	    if(!UIManager._instance){
	        UIManager._instance = new UIManager();
	    }
	    return UIManager._instance;
	}
}
